import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

/*
* @Package: provider
* @ClassName: provider_widget
* @Author: szj
* @CreateDate: 7/28/21 10:10 AM
*/

class ProviderWidget<T extends ChangeNotifier> extends StatefulWidget {
  //数据
  final T model;

  final Widget child;

  //第一次请求网络数据初始化
  final Function(T) onModelInit;

  final Widget Function(BuildContext context, T model, Widget child) builder;

  const ProviderWidget({
    Key key,
    @required this.model,
    @required this.builder,
    this.onModelInit,
    this.child,
  }) : super(key: key);

  @override
  _ProviderWidgetState createState() => _ProviderWidgetState<T>();
}

class _ProviderWidgetState<T extends ChangeNotifier>
    extends State<ProviderWidget<T>> {

  T model;

  @override
  void initState() {
    super.initState();
    model = widget.model;
    if (widget.onModelInit != null && model != null) {
      widget.onModelInit(model);
    }
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      //model 处理数据
      create: (_) => model,
      //child 刷新数据
      child: Consumer<T>(
        builder: widget.builder,
        child: widget.child,
      ),
    );
  }
}
